package com.zy.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;


import java.util.Calendar;

import java.util.HashMap;
import java.util.Map;

/**
 * @author LittleDesire
 * @description
 * @date 2022-04-07 周四 20:56
 * @since 17
 */
public class JwtUtils {
    private String sign = "desire";


    /**
     * 生成Token令牌
     *
     * @param payload 负载数据
     * @param minutes 令牌有效期
     * @return 令牌
     */
    public String getToken(Map<String, String> payload, int minutes) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, minutes);
        JWTCreator.Builder builder = JWT.create();
        if (payload != null) {
            payload.forEach(builder::withClaim);
        }
        return builder.withExpiresAt(calendar.getTime()).sign(Algorithm.HMAC256(sign));
    }


    /**
     * 获取令牌的负载数据
     *
     * @param token 令牌
     * @return Map集合
     */
    public Map<String, String> getPayload(String token) {
        Map<String, String> map = new HashMap<>();
        if (verifyToken(token)) {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(sign)).build();
            DecodedJWT verify = jwtVerifier.verify(token);
            Map<String, Claim> claims = verify.getClaims();
            for (String key : claims.keySet()) {
                map.put(key, "exp".equalsIgnoreCase(key) ? String.format("%tF %<tT", claims.get(key).asDate()) : claims.get(key).asString());
            }
        }
        return map;
    }


    /**
     * 校验令牌
     *
     * @param token 令牌
     * @return 该令牌是否能用
     */
    public boolean verifyToken(String token) {
        boolean flag = false;
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(sign)).build();
        try {
            jwtVerifier.verify(token);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }


    public JwtUtils() {
    }

    public JwtUtils(String sign) {
        this.sign = sign;
    }

    public String getSign() {
        return sign;
    }

    public void setSign(String sign) {
        this.sign = sign;
    }
}
